import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Upload,
  Row,
  Col,
  Space,
  message,
  Spin,
  Typography,
  Divider,
  Switch,
  Tag,
  InputNumber,
  Modal,
} from 'antd';
import type { UploadFile, UploadProps } from 'antd';
import {
  SaveOutlined,
  PlusOutlined,
  DeleteOutlined,
  EyeOutlined,
  UploadOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';
import { ShopService } from '../../services/shopService';
import { UserService } from '../../services/userService';
import { Shop } from '../../types';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

interface ShopFormData {
  name: string;
  description: string;
  logo: string;
  banner: string;
  ownerId: string;
  categories: string[];
  type: 'official' | 'flagship' | 'authorized' | 'personal';
  status: 'active' | 'inactive' | 'suspended' | 'pending';
  contact: {
    phone?: string;
    email?: string;
    address?: string;
    workingHours?: string;
  };
  announcement?: string;
  tags?: string[];
}

const ShopEdit: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [shop, setShop] = useState<Shop | null>(null);
  const [newTag, setNewTag] = useState('');
  const [newCategory, setNewCategory] = useState('');
  const [logoUrl, setLogoUrl] = useState<string>('');
  const [bannerUrl, setBannerUrl] = useState<string>('');
  const [users, setUsers] = useState<any[]>([]);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [formKey, setFormKey] = useState(0); // 用于强制重新渲染表单

  const isEdit = id !== 'create';

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '首页', path: '/' },
      { title: '商店管理', path: '/shops' },
      { title: isEdit ? '编辑商店' : '新增商店' },
    ]));

    if (isEdit) {
      loadShop();
    } else {
      // 新增模式，设置默认值
      const defaultLogo = 'https://via.placeholder.com/200x200/f0f0f0/999999?text=Logo';
      const defaultBanner = 'https://via.placeholder.com/800x300/f0f0f0/999999?text=Banner';

      setLogoUrl(defaultLogo);
      setBannerUrl(defaultBanner);

      form.setFieldsValue({
        status: 'pending',
        type: 'personal',
        categories: [],
        tags: [],
        contact: {},
        logo: defaultLogo,
        banner: defaultBanner,
      });
    }

    // 加载用户列表
    loadUsers();
  }, [id, isEdit, dispatch]);



  const loadShop = async () => {
    if (!id) return;

    try {
      setLoading(true);

      // 从API加载数据
      const shopData = await ShopService.getShop(id);
      console.log('加载的店铺数据:', shopData);
      setShop(shopData);

      // 设置图片URL
      setLogoUrl(shopData.logo || '');
      setBannerUrl(shopData.banner || '');

      // 先重置表单，避免旧数据干扰
      form.resetFields();

      // 准备表单数据
      const formData = {
        name: shopData.name || '',
        description: shopData.description || '',
        logo: shopData.logo || '',
        banner: shopData.banner || '',
        ownerId: shopData.owner?._id || shopData.owner || shopData.ownerId || '',
        categories: shopData.categories || [],
        type: shopData.type || 'personal',
        status: shopData.status || 'pending',
        contact: {
          phone: shopData.contact?.phone || '',
          email: shopData.contact?.email || '',
          address: typeof shopData.contact?.address === 'string'
            ? shopData.contact.address
            : shopData.contact?.address?.detail || '',
          workingHours: shopData.contact?.workingHours || '',
        },
        announcement: shopData.announcement || '',
        tags: shopData.tags || [],
      };

      // 设置表单值
      form.setFieldsValue(formData);

      // 强制重新渲染表单
      setFormKey(prevKey => prevKey + 1);
    } catch (error) {
      console.error('加载商店数据失败:', error);
      console.error('错误详情:', error.response || error);
      message.error('加载商店数据失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const loadUsers = async () => {
    try {
      setLoadingUsers(true);
      const response = await UserService.getUsers({ page: 1, limit: 100 });
      // 后端返回格式: { success: true, data: [...], pagination: {...} }
      setUsers(response.data || []);
    } catch (error) {
      console.error('加载用户列表失败:', error);
      // 如果API调用失败，设置为空数组避免map错误
      setUsers([]);
      message.error('加载用户列表失败');
    } finally {
      setLoadingUsers(false);
    }
  };

  // 保存商店
  const handleSave = async (values: ShopFormData) => {
    // 验证必填字段
    if (!values.name || !values.description || !values.ownerId) {
      message.error('请填写所有必填字段');
      return;
    }

    try {
      setSaving(true);

      // 准备提交数据
      const submitData = {
        ...values,
        // 将ownerId映射为owner字段
        owner: values.ownerId,
        // 处理联系信息中的地址字段
        contact: {
          ...values.contact,
          // 如果地址是字符串，转换为对象格式
          address: typeof values.contact?.address === 'string'
            ? { detail: values.contact.address }
            : values.contact?.address
        }
      };

      // 删除ownerId字段，避免冲突
      delete submitData.ownerId;

      if (isEdit && id) {
        // 编辑模式
        await ShopService.updateShop(id, submitData);
        message.success('商店更新成功');

        // 刷新数据
        await loadShop();
      } else {
        // 新增模式
        await ShopService.createShop(submitData);
        message.success('商店创建成功');

        // 跳转到商店列表
        navigate('/shops');
      }
    } catch (error: any) {
      console.error('保存商店失败:', error);

      // 显示错误信息
      const errorMessage = error.response?.data?.message || error.message || (isEdit ? '商店更新失败' : '商店创建失败');
      message.error(errorMessage);
    } finally {
      setSaving(false);
    }
  };

  // 处理标签添加
  const handleTagAdd = () => {
    if (!newTag) return;
    const tags = form.getFieldValue('tags') || [];
    if (!tags.includes(newTag)) {
      form.setFieldsValue({ tags: [...tags, newTag] });
    }
    setNewTag('');
  };

  // 处理标签删除
  const handleTagRemove = (tag: string) => {
    const tags = form.getFieldValue('tags') || [];
    form.setFieldsValue({ tags: tags.filter((t: string) => t !== tag) });
  };

  // 处理分类添加
  const handleCategoryAdd = () => {
    if (!newCategory) return;
    const categories = form.getFieldValue('categories') || [];
    if (!categories.includes(newCategory)) {
      form.setFieldsValue({ categories: [...categories, newCategory] });
    }
    setNewCategory('');
  };

  // 处理分类删除
  const handleCategoryRemove = (category: string) => {
    const categories = form.getFieldValue('categories') || [];
    form.setFieldsValue({ categories: categories.filter((c: string) => c !== category) });
  };

  // 上传Logo的属性
  const logoUploadProps: UploadProps = {
    name: 'file',
    // 禁用实际上传
    customRequest: ({ file, onSuccess }) => {
      setTimeout(() => {
        onSuccess?.("ok");
      }, 500);
    },
    showUploadList: false,
    beforeUpload: (file) => {
      const reader = new FileReader();
      reader.readAsDataURL(file as Blob);
      reader.onload = () => {
        // 使用本地文件预览
        const logoUrl = reader.result as string;
        setLogoUrl(logoUrl);
        form.setFieldsValue({ logo: logoUrl });
        message.success(`${file.name} 上传成功`);
      };
      return false;
    },
  };

  // 上传Banner的属性
  const bannerUploadProps: UploadProps = {
    name: 'file',
    // 禁用实际上传
    customRequest: ({ file, onSuccess }) => {
      setTimeout(() => {
        onSuccess?.("ok");
      }, 500);
    },
    showUploadList: false,
    beforeUpload: (file) => {
      const reader = new FileReader();
      reader.readAsDataURL(file as Blob);
      reader.onload = () => {
        // 使用本地文件预览
        const bannerUrl = reader.result as string;
        setBannerUrl(bannerUrl);
        form.setFieldsValue({ banner: bannerUrl });
        message.success(`${file.name} 上传成功`);
      };
      return false;
    },
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <p>加载商店数据...</p>
      </div>
    );
  }

  return (
    <div>
      <div style={{ marginBottom: 16 }}>
        <Button
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate('/shops')}
        >
          返回列表
        </Button>
      </div>

      <Title level={2}>{isEdit ? '编辑商店' : '新增商店'}</Title>

      <Form
        key={formKey}
        form={form}
        layout="vertical"
        onFinish={handleSave}
        onFinishFailed={(errorInfo) => {
          // 显示具体的验证错误
          if (Array.isArray(errorInfo.errorFields)) {
            const errorMessages = errorInfo.errorFields.map(field =>
              `${field.name.join('.')}: ${field.errors.join(', ')}`
            ).join('\n');
            message.error(`表单验证失败:\n${errorMessages}`);
          } else {
            message.error('表单验证失败');
          }
        }}
        initialValues={{
          status: 'pending',
          type: 'personal',
          categories: [],
          tags: [],
          contact: {
            phone: '',
            email: '',
            address: '',
            workingHours: '',
          },
          logo: 'https://via.placeholder.com/200x200/f0f0f0/999999?text=Logo',
          banner: 'https://via.placeholder.com/800x300/f0f0f0/999999?text=Banner',
          announcement: '',
        }}
      >
        <Row gutter={16}>
          <Col span={16}>
            {/* 基本信息 */}
            <Card title="基本信息" style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={24}>
                  <Form.Item
                    label="商店名称"
                    name="name"
                    rules={[
                      { required: true, message: '请输入商店名称' },
                      { min: 1, max: 100, message: '商店名称长度应在1-100个字符之间' }
                    ]}
                  >
                    <Input placeholder="请输入商店名称" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="商店描述"
                    name="description"
                    rules={[
                      { required: true, message: '请输入商店描述' },
                      { min: 1, max: 1000, message: '商店描述长度应在1-1000个字符之间' }
                    ]}
                  >
                    <TextArea rows={4} placeholder="请输入商店描述" showCount maxLength={1000} />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="店主"
                    name="ownerId"
                    rules={[{ required: true, message: '请选择店主' }]}
                  >
                    <Select
                      placeholder="请选择店主"
                      loading={loadingUsers}
                      showSearch
                      filterOption={(input, option) =>
                        (option?.children as unknown as string)?.toLowerCase().includes(input.toLowerCase())
                      }
                    >
                      {Array.isArray(users) && users.map(user => (
                        <Option key={user._id} value={user._id}>
                          {user.name} ({user.email})
                        </Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="商店类型"
                    name="type"
                    rules={[{ required: true, message: '请选择商店类型' }]}
                  >
                    <Select placeholder="请选择商店类型">
                      <Option value="official">官方店铺</Option>
                      <Option value="flagship">旗舰店</Option>
                      <Option value="authorized">授权店铺</Option>
                      <Option value="personal">个人店铺</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="商店状态"
                    name="status"
                    rules={[{ required: true, message: '请选择商店状态' }]}
                  >
                    <Select placeholder="请选择商店状态">
                      <Option value="active">正常</Option>
                      <Option value="pending">待审核</Option>
                      <Option value="suspended">已暂停</Option>
                      <Option value="inactive">已停用</Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>
            </Card>

            {/* 联系信息 */}
            <Card title="联系信息" style={{ marginBottom: 16 }}>
              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="联系电话"
                    name={['contact', 'phone']}
                  >
                    <Input placeholder="请输入联系电话" />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="联系邮箱"
                    name={['contact', 'email']}
                    rules={[
                      { type: 'email', message: '请输入有效的邮箱地址' }
                    ]}
                  >
                    <Input placeholder="请输入联系邮箱" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="联系地址"
                    name={['contact', 'address']}
                  >
                    <Input placeholder="请输入联系地址" />
                  </Form.Item>
                </Col>
                <Col span={24}>
                  <Form.Item
                    label="营业时间"
                    name={['contact', 'workingHours']}
                  >
                    <Input placeholder="例如：周一至周五 9:00-18:00" />
                  </Form.Item>
                </Col>
              </Row>
            </Card>
          </Col>

          <Col span={8}>
            {/* 商店图片 */}
            <Card title="商店图片" style={{ marginBottom: 16 }}>
              <Form.Item
                label="商店Logo"
                name="logo"
                rules={[{ required: false }]}
              >
                <Input hidden />
              </Form.Item>
              <div style={{ marginBottom: 16 }}>
                {logoUrl ? (
                  <div style={{ position: 'relative', width: 'fit-content' }}>
                    <img src={logoUrl} alt="Logo" style={{ maxWidth: '100%', maxHeight: 200, borderRadius: '4px' }} />
                    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'rgba(0,0,0,0.6)', padding: '8px', textAlign: 'center' }}>
                      <Upload {...logoUploadProps}>
                        <Button type="text" icon={<UploadOutlined />} style={{ color: 'white' }}>更换Logo</Button>
                      </Upload>
                    </div>
                  </div>
                ) : (
                  <Upload {...logoUploadProps}>
                    <Button icon={<UploadOutlined />} style={{ width: '100%', height: '120px' }}>
                      <div style={{ marginTop: '10px' }}>点击上传Logo</div>
                    </Button>
                  </Upload>
                )}
              </div>

              <Form.Item
                label="商店Banner"
                name="banner"
              >
                <Input hidden />
              </Form.Item>
              <div>
                {bannerUrl ? (
                  <div style={{ position: 'relative', width: 'fit-content' }}>
                    <img src={bannerUrl} alt="Banner" style={{ maxWidth: '100%', maxHeight: 200, borderRadius: '4px' }} />
                    <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, background: 'rgba(0,0,0,0.6)', padding: '8px', textAlign: 'center' }}>
                      <Upload {...bannerUploadProps}>
                        <Button type="text" icon={<UploadOutlined />} style={{ color: 'white' }}>更换Banner</Button>
                      </Upload>
                    </div>
                  </div>
                ) : (
                  <Upload {...bannerUploadProps}>
                    <Button icon={<UploadOutlined />} style={{ width: '100%', height: '120px' }}>
                      <div style={{ marginTop: '10px' }}>点击上传Banner</div>
                    </Button>
                  </Upload>
                )}
              </div>
            </Card>

            {/* 分类和标签 */}
            <Card title="分类和标签" style={{ marginBottom: 16 }}>
              <Form.Item
                label="经营分类"
                name="categories"
              >
                <Input hidden />
              </Form.Item>
              <div style={{ marginBottom: 16 }}>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <Input
                      placeholder="添加经营分类"
                      value={newCategory}
                      onChange={(e) => setNewCategory(e.target.value)}
                      onPressEnter={handleCategoryAdd}
                    />
                    <Button type="primary" onClick={handleCategoryAdd}>添加</Button>
                  </Space>
                  <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.categories !== currentValues.categories} noStyle>
                    {() => (
                      <div style={{ marginTop: 8 }}>
                        {Array.isArray(form.getFieldValue('categories')) && form.getFieldValue('categories').map((category: string) => (
                          <Tag
                            key={category}
                            closable
                            onClose={() => handleCategoryRemove(category)}
                            style={{ margin: '4px' }}
                          >
                            {category}
                          </Tag>
                        ))}
                      </div>
                    )}
                  </Form.Item>
                </Space>
              </div>

              <Form.Item
                label="商店标签"
                name="tags"
              >
                <Input hidden />
              </Form.Item>
              <div>
                <Space direction="vertical" style={{ width: '100%' }}>
                  <Space>
                    <Input
                      placeholder="添加标签"
                      value={newTag}
                      onChange={(e) => setNewTag(e.target.value)}
                      onPressEnter={handleTagAdd}
                    />
                    <Button onClick={handleTagAdd}>添加</Button>
                  </Space>
                  <Form.Item shouldUpdate={(prevValues, currentValues) => prevValues.tags !== currentValues.tags} noStyle>
                    {() => (
                      <div style={{ marginTop: 8 }}>
                        {Array.isArray(form.getFieldValue('tags')) && form.getFieldValue('tags').map((tag: string) => (
                          <Tag
                            key={tag}
                            closable
                            onClose={() => handleTagRemove(tag)}
                            style={{ margin: '4px' }}
                          >
                            {tag}
                          </Tag>
                        ))}
                      </div>
                    )}
                  </Form.Item>
                </Space>
              </div>
            </Card>

            {/* 商店公告 */}
            <Card title="商店公告">
              <Form.Item
                label="公告内容"
                name="announcement"
                rules={[
                  { max: 200, message: '公告内容不能超过200个字符' }
                ]}
              >
                <TextArea rows={4} placeholder="请输入商店公告" showCount maxLength={200} />
              </Form.Item>
            </Card>
          </Col>
        </Row>

        <div style={{ marginTop: 16, textAlign: 'center' }}>
          <Space>
            <Button onClick={() => navigate('/shops')}>取消</Button>
            <Button
              type="primary"
              htmlType="submit"
              loading={saving}
              icon={<SaveOutlined />}
            >
              {isEdit ? '更新商店' : '创建商店'}
            </Button>
          </Space>
        </div>
      </Form>
    </div>
  );
};

export default ShopEdit;
